﻿using Sustainalytics.AwsS3.Client;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Controversies.BusinessLogic;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;
using Sustainalytics.MongoDB.Extensions;
using Sustainalytics.ReportGenerator.BL;
using Sustainalytics.Utils;
using Sustainalytics.Utils.Configuration;
using Sustainalytics.Utils.Serilog;
using System;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.Controversies.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //  [ClaimsChecker("api/v1/company/esg")]
    [RoutePrefix("api/v1/company")]
    [LogControllerFilter(true, true, false)]
    public class ControversyReportController : ApiController
    {
        private readonly string _clientDWConnectionString;
        private readonly IS3Client _s3Client;
        private readonly IRepositoryCollection<CorporateData> _corpDataCollection;

        public ControversyReportController(
            IRepositoryCollection<CorporateData> corpDataCollection,
            IS3Client s3Client, 
            ConnectionStrings connectionStrings)
        {
            _s3Client = s3Client; 
            _corpDataCollection = corpDataCollection;
            _clientDWConnectionString = connectionStrings.ClientDW;
        }
        
        [Route("{companyId}/controversyReport")]
        public HttpResponseMessage Get(Guid companyId)
        {
            try
            {
                var result = TryGetReportFromFileSystem(companyId);

                ControversiesServiceSerilog.Log.GetCompanyReportIdAsSuccess(companyId);
                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError,
                    string.Format("Failed to generate the Controversy Report with company ID={0} Error:{1}", companyId, ex));
            }
        }

        private string GetFileName(Guid companyId)
        {
            var company = _corpDataCollection.Read(companyId);
            return ReportName.Controversy.GetFullReportName(company.CompanyName, companyId);
        }

        private PdfReportExecutionResult TryGetReportFromFileSystem(Guid companyId)
        {
            var finalLetter = string.Empty;
            if (_clientDWConnectionString.Contains("_A"))
                finalLetter = "_A";
            if (_clientDWConnectionString.Contains("_B"))
                finalLetter = "_B";

            var path = SettingsHelper.Read("ControversyCompanyReportPdfPath", @"p:\ControversyCompanyReportPdf") + finalLetter;

            var fileName = GetFileName(companyId);

            IFileHandler fileHandler = new S3FileHandler(path, fileName);

            PdfReportExecutionResult file;

            if (!fileHandler.FileExists())
            {
                var fileContent = GenerateReportOnDemand(companyId).FileContent;
                file = fileHandler.WriteFile(fileContent);
            }
            else
                file = fileHandler.ReadFile();

            //Remove last 40 chars - Guid.pdf
            //Add the current date
            //Add the pdf extension
            file.FileName = fileName.Remove(fileName.Length - 40) + DateTime.UtcNow.ToString("ddMMyyyy", new CultureInfo("en-US")) + ".pdf";
            file.CompanyId = companyId;

            return file;
        }

        private RenderResult GenerateReportOnDemand(Guid companyId)
        {
            var container = CompositionRoot.GetContainer();
            var rptGen = new CompanyReportGeneration(companyId, container);
            return rptGen.GenerateReport(true);
        }
    }
}
